import React from 'react';
import Container from '../components/Base/Container';
import { connect } from 'dva';
import { Toast, Icon } from 'antd-mobile';
import styles from './ShopsMap.less'
import _ from 'lodash';
import markerImg from '../assets/new/marker.png'
import WxLocation from "../components/location/WxLocation";
import BaiduLocation from "../components/location/BaiduLocation";

let map;
const zoom = 15;  // 地图放大等级
const defaultDistance = 9;
const currentBranch = {};
let location;


//latitude 纬度，longitude 经度

const rad = (d) => {
  return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
};

/**
 * 参入两个坐标，
 * @param lng1
 * @param lat1
 * @param lng2
 * @param lat2
 * @returns {number} 两点之间的公里
 */
const calcDistance = (lng1, lat1, lng2, lat2) => {
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10;
  return s;
};

class ShopsMap extends React.Component {

  state = {
    point: {},
    branchList: [],
    currentBranch: {},
    isShow: false,
    currentLocation: []
  }

  componentWillMount() {
    const currentBranch = JSON.parse(this.props.location.query.branch)
    this.setState({
      currentBranch,
      isShow: true
    })
    if (!this.props.stat.branchList.length) {
      this.props.dispatch({
        type: 'stat/fetchBranchList',
        payload: { shopId: this.props.location.query.shopId || this.props.location.query.shopid, showAll: true },
      });
    }
  }

  componentDidMount() {
    /* 获取当前经纬度*/
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
      location = new WxLocation();
    } else {
      location = new BaiduLocation();
    }
    location.getLocation().then(res => {
      this.setState({
        currentLocation: [
          res.longitude,
          res.latitude,
        ]
      });
    });
    /* ---- */
    document.querySelectorAll('.couponContainer')[0].style.paddingBottom = 0;

    map = new BMap.Map("allmap", { enableMapClick: true });

    // 关闭拖拽
    map.disableDragging();
    let tId = -1
    map.addEventListener("touchmove", function (e) {
      clearTimeout(tId)
      map.enableDragging();

      tId = setTimeout(() => {
        map.disableDragging();
      }, 150)
    });

    this.center();
    this.addAllMarkers();

    // 开启鼠标滚轮缩放
    map.enableScrollWheelZoom(true);
  }

  // 组件更新之后
  componentDidUpdate(prevProps, prevState) {
    if (this.props.stat.branchList !== prevProps.stat.branchList && this.props.stat.branchList.length) {
      if (!map) {
        map = new BMap.Map("allmap", { enableMapClick: true });
      }
      this.center();
      this.addAllMarkers();
    }
  }

  componentWillUnmount() {
    document.querySelectorAll('.couponContainer')[0].style.paddingBottom = '1.2rem';
  }

  center = () => {
    if (this.props.stat.branchList.length) {
      const branch_no = this.props.location.query.branch_no;
      const branch = _.find(this.props.stat.branchList, { branch_no });
      if (branch && branch.location && branch.location.length === 2) {
        const point = new BMap.Point(branch.location[0], branch.location[1]);
        // 显示中间点
        map.centerAndZoom(point, zoom);
      }
    }
  }

  navigation = (lng, lat, branch_name) => {
    const geolocation = new BMap.Geolocation();
    const _this = this;
    geolocation.getCurrentPosition(function (r) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        /*
        if (!r.accuracy) {
          Toast.fail('无法获得精确位置', 1);
          return;
        }
        */

        let mk = new BMap.Marker(r.point);
        map.addOverlay(mk);
        map.panTo(r.point);

        const geoc = new BMap.Geocoder();
        const pt = new BMap.Point(lng, lat);
        geoc.getLocation(pt, (rs) => {
          const addComp = rs.addressComponents;
          window.location.href = `http://api.map.baidu.com/direction
           ?origin=latlng:${r.point.lat},${r.point.lng}|name:我的位置&destination=latlng:${lat},${lng}|name:${branch_name}
           &mode=driving&origin_region=${r.address.city.slice(0, -1)}
           &destination_region=${addComp.city.slice(0, -1)}
           &output=html&src=yourCompanyName|yourAppName`;
        });
      } else {
        Toast.fail('failed' + this.getStatus(), 1);
      }
    }, { enableHighAccuracy: true });
  }

  // 编写自定义函数,创建标注
  addMarker = (lng, lat, branch_name, address, tel, pic) => {
    const point = new BMap.Point(lng, lat);
    const that = this
    //const marker = new BMap.Marker(point);

  /* ---------------------------------------------------- */
    // 复杂的自定义覆盖物
    function NewMarker(point, branchImg) {
      this._point = point;
      this._branchImg = branchImg
    }

    // 继承
    NewMarker.prototype = new BMap.Overlay();

    // 初始化标注
    NewMarker.prototype.initialize = function (map) {
      this._map = map;

      var div = document.createElement("div");
      div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
      div.style.height = "1.328502rem";
      div.style.width = "1.15942rem";
      div.style.background = `url(${markerImg}) 0 0`
      div.style.backgroundSize = "100% 100%"
      div.style.position = 'relative'
      // 门店img
      let branch = document.createElement('div')
      branch.style.width = '.772947rem'
      branch.style.height = '.797101rem'
      branch.style.borderRadius = '50%'
      branch.style.background = `url("${this._branchImg}") 0 0`
      branch.style.backgroundSize = '100% 100%'
      branch.style.position = 'absolute'
      branch.style.left = '.193237rem'
      branch.style.top = '.169082rem'

      div.addEventListener('click', () => {
        const { branchList } = that.state
        let index = branchList.findIndex(v => v.location[0] === point.lng && v.location[1] === point.lat)
        that.setState({
          currentBranch: branchList[index],
          isShow: true
        })
      })

      div.appendChild(branch)

      // 将自定义标注添加到容器上
      map.getPanes().labelPane.appendChild(div);

      // 保存div实例
      this._div = div

      return div;
    }

    // 随着地图放大缩小，标注的位置也要随之改变，draw会被调用
    // 移动标注的位置
    NewMarker.prototype.draw = function () {
      var position = this._map.pointToOverlayPixel(this._point);
      this._div.style.left = position.x - 48 / 2 + "px";    
      this._div.style.top = position.y - 55 / 2 + "px";    
    }

    // 实例化自定义标注
    var newMarker = new NewMarker(point, pic);

  /* ----------------------------------- */
    map.addOverlay(newMarker);

/*     const opts = {
      width: 200,     // 信息窗口宽度
      // height: 60,     // 信息窗口高度
      // title : `门店：${branch_name}` , // 信息窗口标题
      enableMessage: true, // 设置允许信息窗发送短息
      // message:"亲耐滴，晚上一起吃个饭吧？戳下面的链接看下地址喔~"
    };

    const dom = document.createElement('div');
    const div = document.createElement('div');
    div.innerHTML = `<div style="margin-top: 0.5em">门店：${branch_name}</div><div style="margin-top: 0.5em">电话：${tel || ''}</div><div style="margin-top: 0.5em">地址：${address}</div>`;
    dom.appendChild(div);

    if (pic && pic.length) {
      const div = document.createElement('div');
      div.style.marginTop = '0.5em';
      dom.appendChild(div);
      for (const item of pic) {
        const img = document.createElement('img');
        img.style.maxWidth = '92px';
        img.style.maxHeight = '92px';
        img.style.margin = '0 10px 10px 0';
        img.src = item;
        // btn.addEventListener('click', this.navigation.bind(this, lng, lat, branch_name));
        div.appendChild(img);
      }
    }

    const btn = document.createElement('button');
    btn.style.marginTop = '0.5em';
    btn.innerHTML = '导航';
    btn.addEventListener('click', this.navigation.bind(this, lng, lat, branch_name));
    dom.appendChild(btn);

    if (tel) {
      const btn2 = document.createElement('button');
      btn2.style.marginTop = '0.5em';
      btn2.style.marginLeft = '1em';
      btn2.innerHTML = '拨打电话';
      btn2.addEventListener('click', () => { window.location.href = `tel:${tel}`; });
      dom.appendChild(btn2);
    } */

    // dom.innerHTML=`地址：${address}<br/><button onclick=alert(lng)>导航</button>`


    //const infoWindow = new BMap.InfoWindow(dom, opts);  // 创建信息窗口对象
    /* newMarker.addEventListener("click", () => {
      //map.openInfoWindow(infoWindow, point); // 开启信息窗口
      // 传递数据给state
      const { branchList } = that.state
        let index = branchList.findIndex(v => v.location[0] === point.lng && v.location[1] === point.lat)
        that.setState({
          currentBranch: branchList[index],
          isShow: true
        }, () => {
          map.addEventListener("touchend", function (e) {
            // 开启拖拽
            map.enableDragging();
          });
        })
    }); */
    /*     if (currentBranch.location && currentBranch.location['0'] === lng && currentBranch.location['1'] === lat) {
          map.openInfoWindow(infoWindow, point);
        } */
  }

  addAllMarkers = () => {
    this.setState({
      branchList: this.props.stat.branchList
    })

    this.props.stat.branchList.length &&
      this.props.stat.branchList.map((item) => {
        if (item.location) {
          this.addMarker(item.location['0'], item.location['1'], item.branch_name, item.qez_address, item.qez_tel, item.qez_pic);
        }
      });
  }

  render() {
    const height = document.documentElement.clientHeight;
    const { currentBranch, isShow } = this.state
    const distance = calcDistance(currentBranch.location[0], currentBranch.location[1], this.state.currentLocation[0], this.state.currentLocation[1])
    return (
      <div>
      <Container className="couponContainer" title="附近的门店" >
        <div className={styles['storeWrap']}>
          <div className={styles['store']}>
            <span onClick={() => this.props.history.goBack()}><Icon key="1"  size="md" type="left" /></span>
            <span>附近的门店</span>
          </div>
        </div>
        <div className={styles['infoWrap']} style={{ display: isShow ? 'block' : 'none' }}>
          <div className={styles["infoTitle"]}>{currentBranch.branch_name}</div>
          <div className={styles["infoAddWrap"]}>
            <span>{currentBranch.dis ? currentBranch.dis : this.state.currentLocation.length ? (distance < 1000 ? `${distance}m` : `${(distance / 1000).toFixed(2)}km`) : ''}</span>
            <span>{currentBranch.qez_address}</span>
          </div>
          <div className={styles["infoPhone"]}>
            <span onClick={() => this.navigation(currentBranch.location[0], currentBranch.location[1], currentBranch.branch_name)}>导航</span>
            <span onClick={() => { window.location.href = `tel:${currentBranch.qez_tel}`; }}>拨打电话</span>
          </div>
        </div>
        <div id="allmap" style={{ width: '100%', height, overflow: 'hidden', fontFamily: '微软雅黑' }} />
      </Container>
      </div>
    );
  }
}

// 将state传进shopMap
export default connect(({ stat }) => ({ stat }))(ShopsMap);
